package com.mjh.zhujianju.service.base.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.google.gson.annotations.SerializedName;
import com.livew.framework.base.service.impl.BaseServiceImpl;
import com.livew.framework.exception.XTBusinessException;
import com.livew.framework.utils.XTListUtils;
import com.mjh.zhujianju.dao.base.ContentMapper;
import com.mjh.zhujianju.model.base.ContentEO;
import com.mjh.zhujianju.service.base.ContentService;

/**
 * @author liuyang
 * @Description: 内容
 * @date 2018/8/11 17:30
 */
@Service
public class ContentServiceImpl extends BaseServiceImpl<ContentEO> implements ContentService {

	@Autowired
	private ContentMapper contentMapper;
	
	@Resource
	private HttpServletRequest request;

	public ContentServiceImpl(ContentMapper contentMapper) {
		super(contentMapper);
	}

	
	@Override
	public ContentEO queryContentByTypeAndId(String type, Long businessId) {
		ContentEO contentEO = new ContentEO();
		contentEO.setType(type);
		contentEO.setBusinessId(businessId);
		List<ContentEO> list = contentMapper.selectListByCondition(contentEO);
		if (CollectionUtils.isEmpty(list)) {
			return null;
		}
		ContentEO c  = list.get(0);
		if(c.getContent()!=null&&c.getContent().contains("src=\"/file/showImage")) {
			String url2= request.getScheme()+"://"+ request.getServerName()+":"+request.getServerPort()+request.getContextPath();
			String src = url2+"/file/showImage";
			String content = c.getContent().replaceAll("/file/showImage", src);
			c.setContent(content);
		}
		return list.get(0);
	}

	@Override
	public void saveOrUpdate(String type, Long businessId, String content) throws XTBusinessException {
		ContentEO contentEO = new ContentEO();
		contentEO.setType(type);
		contentEO.setBusinessId(businessId);
		List<ContentEO> list = contentMapper.selectListByCondition(contentEO);
		if(XTListUtils.isEmpty(list)) {
			contentEO.setContent(content);
			this.save(contentEO);
		}else {
			contentEO =	list.get(0);
			contentEO.setContent(content);
			this.updateByPrimaryKey(contentEO);
		}
	}

	@Override
	public Map<Long,ContentEO> queryContentsByTypeAndId(String type, List<Long> businessIds) {
		if(XTListUtils.isEmpty(businessIds)) {
			return null;
		}
		List<ContentEO> list = contentMapper.selectListBybusinessIds(type,businessIds);
		if(!XTListUtils.isEmpty(list)) {
			 Map<Long,ContentEO> map = new HashMap<>();
			 for (ContentEO contentEO : list) {
				 map.put(contentEO.getBusinessId(), contentEO);
			}
			 return map;
		}
		return null;
	}

}
